package org.walklink.core.event;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.walklink.common.entity.DefaultTrackDto;
import org.walklink.common.entity.jvm.JvmTrackDto;
import org.walklink.common.enums.EventTypeEnum;
import org.walklink.common.util.JsonUtil;
import org.walklink.common.util.JvmStackUtil;
import org.walklink.core.plugins.DefaultPluginManager;
import org.walklink.core.plugins.client.IClientPlugin;

import java.nio.charset.StandardCharsets;

/**
 * 事件处理类 - JVM
 *
 * @author lidishan
 */
public class JvmEventHandler extends AbstractEventHandler {

    private static final IClientPlugin PLUGIN = DefaultPluginManager.loadPrimary(IClientPlugin.class);
    private static final Logger LOGGER = LoggerFactory.getLogger(JvmEventHandler.class);

    @Override
    public void send() {
        // 这个要直接发就好了，不用分批发
        JvmTrackDto allJvmInfo = JvmStackUtil.getAllJvmInfo();
        DefaultTrackDto<JvmTrackDto> obj = new DefaultTrackDto<>(EventTypeEnum.JVM_SYN, allJvmInfo);
        String jsonStr = JsonUtil.silentObject2String(obj);
        if (StringUtils.isBlank(jsonStr)) {
            LOGGER.error("ClientInitializer upd send jsonStr null error obj={}", obj);
            return;
        }
        try {
            byte[] bytes = jsonStr.getBytes(StandardCharsets.UTF_8);
            PLUGIN.send(bytes);
        } catch (Exception e) {
            LOGGER.error("ClientInitializer init upd send error obj={}", obj, e);
        }
    }

    @Override
    public void receive(DefaultTrackDto<?> trackDto) {
        JvmTrackDto data = JsonUtil.silentString2Object(JsonUtil.silentObject2String(trackDto.getData()), JvmTrackDto.class);
        LOGGER.info("UdpServerHandler channelRead0 先打印着======JVM消息同步信息为：{}", JsonUtil.silentObject2String(data));
    }
}
